package moni.anyou.com.view.view.addresslist;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.HorizontalScrollView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONObject;
import org.kymjs.aframe.http.KJHttp;
import org.kymjs.aframe.http.KJStringParams;
import org.kymjs.aframe.http.StringCallBack;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import android.content.Intent;
import moni.anyou.com.view.R;
import moni.anyou.com.view.base.BaseFragment;
import moni.anyou.com.view.bean.request.ReqHomeBean;
import moni.anyou.com.view.bean.response.ResHomeData;
import moni.anyou.com.view.config.SysConfig;
import moni.anyou.com.view.tool.AppTools;
import moni.anyou.com.view.view.fragmentadapter.FragmentAdapter;
import moni.anyou.com.view.widget.NetProgressWindowDialog;
import moni.anyou.com.view.widget.utils.view.ViewUtil;

public class FamilyFragment extends BaseFragment{
    private ListView sortListView;
    private SideBar sideBar;
    private TextView dialog;
    private SortAdapter adapter;
    private ClearEditText mClearEditText;
    private View mView;
    private int typeid = 1;
    private NetProgressWindowDialog window;
    private boolean isVisible = false;
    /**
     * 汉字转换成拼音的类
     */
    private CharacterParser characterParser;
    private List<SortModel> SourceDateList=new ArrayList<>();

    /**
     * 根据拼音来排列ListView里面的数据类
     */
    private PinyinComparator pinyinComparator;

    //private String[] name = new String[1000];
    //private String[] phone=  new String[1000];


    public FamilyFragment() {
    }

    public void setTypeid(int typeid) {
        this.typeid = typeid;
    }
    @Override
    public void onResume() {
        super.onResume();
        //getdata();
    }

    @Override
    public void setData() {
        super.setData();
//        JSONArray aa = Tools.getModuleJsonArray("live");
        if (isVisible) {
            getdata();
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        isVisible = isVisibleToUser;

    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        mView = inflater.inflate(R.layout.fragment_family, container, false);

        init(mView);
        return mView;

    }



    @Override
    public void initView() {
        super.initView();
        window = new NetProgressWindowDialog(mBaseActivity);
        //实例化汉字转拼音类
        characterParser = CharacterParser.getInstance();

        pinyinComparator = new PinyinComparator();

        sideBar = (SideBar) mView.findViewById(R.id.sidrbar);
        dialog = (TextView) mView.findViewById(R.id.dialog);
        sideBar.setTextView(dialog);

        //设置右侧触摸监听
        sideBar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {

            @Override
            public void onTouchingLetterChanged(String s) {
                //该字母首次出现的位置
                int position = adapter.getPositionForSection(s.charAt(0));
                if(position != -1){
                    sortListView.setSelection(position);
                }

            }
        });

        sortListView = (ListView)mView.findViewById(R.id.country_lvcountry);
        sortListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                //这里要利用adapter.getItem(position)来获取当前position所对应的对象
                //Toast.makeText(getActivity(), ((SortModel)adapter.getItem(position)).getName(), Toast.LENGTH_SHORT).show();
                call(((SortModel)adapter.getItem(position)).getPhone());
            }
        });

//		for (int i=0;i<name.length;i++){
//			SortModel sortModel=new SortModel();
//			sortModel.setName(name[i]);
//			sortModel.setPhone(phone[i]);
//			SourceDateList.add(sortModel);
//		}


        mClearEditText = (ClearEditText) mView.findViewById(R.id.filter_edit);
       // mClearEditText.clearFocus();
        //mClearEditText.clearFocus();
       //mClearEditText.setFocusable(false);
        //根据输入框输入值的改变来过滤搜索
        mClearEditText.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //当输入框里面的值为空，更新为原来的列表，否则为过滤数据列表
                filterData(s.toString());
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }
    /** 
      * 调用拨号界面 
      * @param phone 电话号码 
      */
    private void call(String phone) {
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phone));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }
    /**
            * 为ListView填充数据
    * @param date
    * @return
            */
    /*
    private List<SortModel> filledData(String [] date,String[] phone){
        List<SortModel> mSortList = new ArrayList<SortModel>();

        for(int i=0; i<date.length; i++){
            SortModel sortModel = new SortModel();
            sortModel.setName(date[i]);
            sortModel.setPhone(phone[i]);
            //汉字转换成拼音
            String pinyin = characterParser.getSelling(date[i]);
            String sortString = pinyin.substring(0, 1).toUpperCase();

            // 正则表达式，判断首字母是否是英文字母
            if(sortString.matches("[A-Z]")){
                sortModel.setSortLetters(sortString.toUpperCase());
            }else{
                sortModel.setSortLetters("#");
            }

            mSortList.add(sortModel);
        }
        return mSortList;

    }
   */
    /**
     * 为ListView填充数据
     * @return
     */
    private List<SortModel> filledData(JSONArray arr){
        try {
            List<SortModel> mSortList = new ArrayList<SortModel>();

            for (int i = 0; i < arr.length(); i++) {
                SortModel sortModel = new SortModel();
                String name = ((JSONObject) arr.get(i)).getString("nick");
                String phone = ((JSONObject) arr.get(i)).getString("mobile");
                sortModel.setName(name);
                sortModel.setPhone(phone);
                //汉字转换成拼音
                if (!name.equals("")) {
                    String pinyin = characterParser.getSelling(name);
                    String sortString = pinyin.substring(0, 1).toUpperCase();


                    // 正则表达式，判断首字母是否是英文字母
                    if (sortString.matches("[A-Z]")) {
                        sortModel.setSortLetters(sortString.toUpperCase());
                    } else {
                        sortModel.setSortLetters("#");
                    }
                }
                else{
                    sortModel.setSortLetters("#");
                }

                mSortList.add(sortModel);
            }
            return mSortList;
        }
        catch(Exception ex){

            return  new ArrayList<SortModel>();
        }
    }

    /**
     * 根据输入框中的值来过滤数据并更新ListView
     * @param filterStr
     */
    private void filterData(String filterStr){
        List<SortModel> filterDateList = new ArrayList<SortModel>();

        if(TextUtils.isEmpty(filterStr)){
            filterDateList = SourceDateList;
        }else{
            filterDateList.clear();
            for(SortModel sortModel : SourceDateList){
                String name = sortModel.getName();
                if(name.indexOf(filterStr.toString()) != -1 || characterParser.getSelling(name).startsWith(filterStr.toString())){
                    filterDateList.add(sortModel);
                }
            }
        }

        // 根据a-z进行排序
        Collections.sort(filterDateList, pinyinComparator);
        adapter.updateListView(filterDateList);
    }

    public void getdata() {
        KJHttp kjh = new KJHttp();
        KJStringParams params = new KJStringParams();
        final String cmdPara = "{\"cmd\":\"24\",\"uid\":\""+ SysConfig.uid + "\",\"typeid\":\""+ typeid + "\",\"token\":\""+ SysConfig.token + "\",\"cid\":\""+ SysConfig.cid + "\"}";
        params.put("sendMsg", cmdPara);
        window.ShowWindow();
        kjh.urlGet(SysConfig.ServerUrl, params, new StringCallBack() {
            @Override
            public void onSuccess(String t) {

                Log.d(TAG, "onSuccess: " + t);
                try {
                    JSONObject jsonObject = new JSONObject(t);

                    int result = Integer.parseInt(jsonObject.getString("result"));
                    if (result >= 1) {
                        JSONArray jsonArr =  (JSONArray) jsonObject.get("list");
                        if ( jsonArr.length() > 0) {
                            SourceDateList = filledData(jsonArr);
                            // 根据a-z进行排序源数据
                            Collections.sort(SourceDateList, pinyinComparator);
                            adapter = new SortAdapter(getActivity(), SourceDateList);
                            sortListView.setAdapter(adapter);
                        }

                    } else {
                        if (result == -2) {
                            AppTools.jumptoLogin(mBaseActivity);
                        }
                        else {
                            Toast.makeText(mContext, jsonObject.get("retmsg").toString(), Toast.LENGTH_SHORT).show();
                        }
                    }
                } catch (Exception ex) {
                    window.closeWindow();
                    Toast.makeText(mContext, "数据请求失败", Toast.LENGTH_SHORT).show();
                }
                window.closeWindow();
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                Toast.makeText(mContext, "网络异常，请稍后再试", Toast.LENGTH_SHORT).show();

                window.closeWindow();
            }
        });
    }

}
